package mianxiangduixiang.Test8;

import javax.swing.*;
import java.awt.*;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;

/**
 * @Author JetZhang
 * Package:mianxiangduixiang.Test8
 * Description:一个有两个文本区的小应用程序,当一个文本区中输入若干个数时,另一个文本区同时对所输入的数进行求和运算并求出平均值,也就是说随着输入的变化, 另一个文本区不断地更新求和及平均值
 * @Date 2021/11/18
 */

public class T4 {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        TextArea area1 = new TextArea();
        JLabel area2 = new JLabel("数字请用逗号隔开");
        GridLayout gridLayout = new GridLayout(1, 2,10,10);
        frame.setLayout(gridLayout);
        frame.add(area1);
        frame.add(area2);
        area1.addTextListener(new TextListener() {
            @Override
            public void textValueChanged(TextEvent e) {
                String text = area1.getText();
                if (text.contains("，")){
                    text = text.replace("，", ",");
                    area1.setText(text);
                    area2.setText("数字请用英文逗号隔开");
                }
                String[] split = text.split(",");
                double sum = 0;
                double avg = 0;
                for (int i = 0; i < split.length; i++) {
                    avg+=Double.valueOf(split[i])/split.length;
                    sum+=Double.valueOf(split[i]);
                }
                area2.setText("总和："+sum+"      \n平均："+avg);

            }
        });
        frame.setSize(400, 200);
        frame.setVisible(true);

    }
}
